import { Button, Form, message } from 'antd';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import type { FormNoticeType } from '@/pages/Notice/data';
import { createCategory } from '@/pages/Category/service';
import type { CurrentUser } from '@/models/user';
const formLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
interface UpdateFormProps {
  setRefreshCount: any;
  currentUser: CurrentUser;
}
const CreateModalForm = (props: UpdateFormProps) => {
  const { setRefreshCount, currentUser } = props;
  const [form] = Form.useForm();

  /**
   * 创建节点
   * @param fields
   */
  const handleCreate = async (fields: FormNoticeType) => {
    const hide = message.loading('正在创建');
    try {
      const res = await createCategory({
        ...fields,
        user_id: currentUser.ID,
      });
      hide();
      if (res.success) {
        form.resetFields();
        setRefreshCount((count: number) => count + 1);
        message.success('创建成功');
      } else {
        message.error('创建失败,请重试');
      }
      return true;
    } catch (error) {
      hide();
      message.error('创建失败,请重试');
      return false;
    }
  };
  return (
    <ModalForm
      form={form}
      layout="horizontal"
      {...formLayout}
      title="添加分类"
      modalProps={{
        onCancel: () => form.resetFields(),
      }}
      initialValues={{
        is_show: true,
      }}
      trigger={<Button type="primary">添加</Button>}
      onFinish={async () => {
        form
          .validateFields()
          .then((fieldsValue) => {
            handleCreate(fieldsValue);
          })
          .catch(() => {});
        return true;
      }}
    >
      <ProFormText
        width={256}
        key="name"
        name="name"
        label="分类名"
        rules={[{ required: true, message: '请输入分类名' }]}
      />
    </ModalForm>
  );
};
export default CreateModalForm;
